/*
Copyright (c) 2010, Luca Deltodesco
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions
	  and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of
	  conditions and the following disclaimer in the documentation and/or other materials provided
	  with the distribution.
    * Neither the name of the caxe project nor the names of its contributors may be used to endorse
	 or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

package;

import neko.FileSystem;
using SUse;
using SUtil;
import Types;
import SUse;

class FUtil {
	
	public static inline function fix(path:String,?dir:Bool=false) {
		path = (~/[\/\\]+/g).replace(path, '/');
		if (dir) {
			//if (path.cat(path.length - 1) != '/'._c()) return path + "/";
			if (path.cat(path.length - 1) == '/'._c()) return path.substr(0, path.length - 1);
			else return path;
		}else return path;
	}
	
	//----------------------------------------------------------------------------------------------
	
	public static inline function isFile(path:String) {
		path = fix(path);
		return FileSystem.exists(path) && FileSystem.kind(path) == kfile;
	}
	public static inline function isDirectory(path:String) {
		path = fix(path, true);
		return FileSystem.exists(path) && FileSystem.kind(path) == kdir;
	}
	
	//----------------------------------------------------------------------------------------------
	
	public static inline function filename(path:String) {
		path = fix(path);
		var ind = path.rfind_first_char('/'._c());
		if (ind != SUtil.npos) path = path.substr(ind + 1);
		
		ind = path.rfind_first_char('.'._c());
		if (ind != SUtil.npos) path = path.substr(0, ind);
		
		return path;
	}
	public static inline function extension(path:String) {
		path = fix(path);
		var ind = path.rfind_first_char('.'._c());
		if (ind != SUtil.npos) return path.substr(ind + 1);
		else return "";
	}
	public static inline function directory(path:String) {
		path = fix(path);
		var ind = path.rfind_first_char('/'._c());
		if (ind != SUtil.npos) return path.substr(0, ind + 1);
		else return "";
	}
	
	//----------------------------------------------------------------------------------------------
	
	public static inline function mkdir(path:String) {
		path = fix(path, true);
		var paths = path.split('/');
		var cpath = "";
		if (paths[0].find_first_char(':'._c()) != SUtil.npos) {
			cpath += paths[0]+"/";
			paths.shift();
		}
		for (i in paths) {
			cpath += i + "/";
			if (!(~/[a-zA-Z0-9\-_]/g).match(cpath)) continue;
			var tpath = fix(cpath, true);
			if (!FileSystem.exists(tpath)) {
				FileSystem.createDirectory(tpath);
			}
		}
	}
	
	//----------------------------------------------------------------------------------------------
	
	public static inline function pathDotSlash(path:String) {
		return (~/\./g).replace(path, '/');
	}
	public static inline function pathSlashDot(path:String) {
		return (~/\//g).replace(fix(path), '.');
	}
	
	//----------------------------------------------------------------------------------------------
	
	public static function recurse(path:String, files:Array<String>) {
		path = fix(path, true);
		if (isDirectory(path)) {
			path += "/";
			for (f in FileSystem.readDirectory(path)) {
				var fp = path + f;
				if (isFile(fp) && extension(fp) == CaxeInfo.st)
					files.push(fp);
				else if (isDirectory(fp))
					recurse(fp, files);
			}
		}
	}
	
	public static function cxopen(path:String) {
		path = fix(path);
		var fname = filename(path);
		if (CaxeInfo.files.exists(fname)) return null;
		
		var ret = new File();
		ret.path = path;
		ret.name = fname;
		
		var nsc = new Scope();
		nsc.actfile = ret;
		ret.data = nsc;
		nsc.file = nsc;
		nsc.parent = nsc.method = nsc.object = null;
		
		var nent = new Datum(dString);
		nent.str = neko.io.File.getContent(path);
		nsc.data.push(nent);
		
		if (nent.str.cat(0) == 0xef)
			nent.str = nent.str.substr(3);
			
		CaxeInfo.files.set(fname, ret);
		return ret;
	}
	
	public static function cxwrite(path:String, dat:String, nice:Bool) {
		var f = neko.io.File.write(path, false);
		if (nice) {
			dat = (~/[ ]+/g).replace(dat, ' ');
			dat = (~/^[ \t]+/g).replace(dat, '');
			dat = (~/[\n\r]+([ \t]+)/g).replace(dat, '\n');
			dat = (~/([ \t]+)[\n\r]+/g).replace(dat, '\n');
			dat = (~/[ \t]+$/g).replace(dat, '');
			dat = (~/[\t]+/g).replace(dat, '');
			dat = (~/[\n\r]+/g).replace(dat, '\n');
			
			dat = String.fromCharCode(0xef) + String.fromCharCode(0xbb) + String.fromCharCode(0xbf) + "/**/ " + dat;
			
			var cnt = 0;
			var i = Integer.get(0);
			while (i.i < dat.length) { 
				dat.skipstr(i);
				
				if      (dat.iat(i) == '{'._c()) cnt++;
				else if (dat.iat(i) == '}'._c()) cnt--;
				else if (dat.iat(i) == '\n'._c()) {
					var num = cnt;
					if ((i.i + 1) < dat.length && dat.cat(i.i + 1) == '}'._c()) {
						num--;
					}
					var tab = "";
					for (j in 0...num) tab += "    ";
					dat = dat.substr(0, i.i + 1) + "/**/ " + tab + dat.substr(i.i + 1);
				}
				i.i++;
			}
		}
		f.writeString(dat);
		
		f.flush();
		f.close();
	}
}
